class Match < ActiveRecord::Base
     has_many :users_matches, class_name: 'UsersMatch'
     has_many :users, through: :users_matches

     validates_numericality_of :startmoney, :allow_nil => false,
     :greater_then => 0, :message => "The value of start money must be greather than zero."

     #checking that the owner is a valid user
     validate :check_owner
     def check_owner
          if((User.find_by(owner)) == nil)
               errors.add(:owner, "Invalid owner of game.")
          end
     end

     def ownerMatch 
          self.users_matches.each do |um|
               return um if um.user_id = self.owner
          end
     end

     def finished
          return Time.now > self.begintime + self.timealloted.days
     end

     def pending
          return self.begintime > Time.now
     end

     def dropUnjoined
          for um in self.users_matches do
               um.delete if not um.joined
          end
     end
     
     def timeLeft
          secs = (self.begintime + self.timealloted.days - DateTime.now).to_i
          mins  = secs / 60
          hours = mins / 60
          days  = hours / 24
          
          if days > 0
               "#{days} days and #{hours % 24} hours"
          elsif hours > 0
               "#{hours} hours and #{mins % 60} minutes"
          elsif mins > 0
               "#{mins} minutes and #{secs % 60} seconds"
          elsif secs >= 0
               "#{secs} seconds"
          end
     end
end
